<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BUIAttribute
 *
 * @author jianfeng
 */
class BUIAttribute extends BUIThemedControl {

    //put your code here

    public function prepareAttributeView($attributeTable, $owner, $mediaIndex, $model = NULL, $control = NULL) {

        //$updateControl = Blyn::app()->getUIManager()->getUpdateControl();

        if ($model == NULL)
            $model = new BDynamicFormModel();
        $attributeNameField = 'media_name_add_attribute';
        $attributeAliasField = 'media_alias_add_attribute';
        $attributeTypeField = 'media_type_add_attribute';
        $model->addField($attributeNameField);
        $model->addField($attributeAliasField);
        $model->addField($attributeTypeField);

        $viewData = array();
        $viewData['owner'] = $owner;
        $viewData['model'] = $model;
        $viewData['mediaIndex'] = $mediaIndex;
        $viewData['attributeNameField'] = $attributeNameField;
        $viewData['attributeAliasField'] = $attributeAliasField;
        $viewData['attributeTypeField'] = $attributeTypeField;

        if (is_string($attributeTable) && $owner instanceof BEntity) {
            $attributeTable = new BASheet($attributeTable, $owner);
        }

        if ($attributeTable instanceof BTreeTable) {
            $attributeView = $attributeTable->getView();
            $viewData['attributeView'] = $attributeView;
            $attrTableName = $attributeTable->getTableName();
            $viewData['attributeTable'] = $attrTableName;
            if (!$owner instanceof BEntity)
                $owner = $attributeTable->getOwner();
        }

        if ($owner instanceof BEntity) {
            $viewData['ownerClass'] = get_class($owner);
            $viewData['ownerType'] = 'BEntity';
            $viewData['ownerId'] = $owner->getId();
        }

        if ($owner instanceof BTreeList) {
            $listNode = $owner->getListNode();
            $viewData['ownerClass'] = get_class($listNode);
            $viewData['ownerId'] = $owner->getId();
            $viewData['ownerType'] = 'BTreeList';
        }

        if ($control == NULL) {
            $control = $this;
        }
        $control->addRenderView('addAttribute', 'attribute_add', $viewData);
    }

    public function onShowAddAttribute($attributeTable, $owner, $mediaIndex, $model = NULL) {
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $this->prepareAttributeView($attributeTable, $owner, $mediaIndex, $model, $updateControl);
    }

    public function onAddAttribute($data = NULL) {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $ownerClass = $activeLink->getLinkVariable('ownerClass');
        $ownerId = $activeLink->getLinkVariable('ownerId');
        $ownerType = $activeLink->getLinkVariable('ownerType');
        $attributeTableName = $activeLink->getLinkVariable('attributeTable');
        $mediaIndex = $activeLink->getLinkVariable('mediaIndex');
        $postManager = new BPostManager();
        $postData = $postManager->parsedModelData();

        $mediaList = $postManager->populateMediaListFromPostData($postData, 'add_attribute');

        $itemData = array();
        $itemData['name'] = $mediaList['name']->content;
        $itemData['alias'] = $mediaList['alias']->content;
        $itemData['type'] = $mediaList['type']->content;

        if ($ownerType == 'BEntity' && $ownerClass != NULL && $ownerId > 0) {
            $owner = new $ownerClass($ownerId);
        }

        if ($ownerType == 'BTreeList' && $ownerClass != NULL && $ownerId > 0) {
            $treeItem = new $ownerClass();
            $treeTable = new BTreeTable($treeItem);
            $owner = $treeTable->getListById($ownerId);
        }

        $attributeTable = new BASheet($attributeTableName, $owner);

        $list = $attributeTable->getList(array('itemData' => $itemData));
        if ($list == NULL) {
            $attributeTable->addList($itemData);
        }

        
        $this->onShowAddAttribute($attributeTable, $owner, $mediaIndex);
    }

    /**
     * this function use to populate model for owner from attribute
     * @param type $model
     * @param type $attributeTable
     */
    public function populateModelFromAttribute(&$model, $owner, $attributeTable, $mediaIndex) {
        //add product attribute
        //$attributeTable = new BPProductSheet('productAttribute', $product);
        $attributeView = $attributeTable->getView();

        if ($model instanceof BDynamicFormModel) {
            foreach ($attributeView as $id => $list) {
                $field = $this->getModelFieldByAttribute($list, $mediaIndex);
                $model->addField($field);
                $name = $list->getItem('name')->getValue();
                //assign attribute value to model
                if ($owner instanceof BTreeList && $owner->getItem($name) != NULL) {
                    $model->$field = $owner->getItem($name)->getValue();
                }
                if ($owner instanceof BEntity) {
                    $model->$field = $owner->$name;
                }
            }
        }
    }

    public function getModelFieldByAttribute($attributeList, $mediaIndex) {

        if ($attributeList instanceof BTreeList) {
            $attrName = $attributeList->getItem('name')->getValue();
            $attrAlias = $attributeList->getItem('alias')->getValue();
            $attrType = $attributeList->getItem('type')->getValue();

            if (strtolower($attrType) == 'image') {
                return 'image_media_' . $attrName . '_' . $mediaIndex;
            } else {
                return 'media_' . $attrName . '_' . $mediaIndex;
            }
        }

        return FALSE;
    }

    public function getDataTypeList($data = NULL) {
        $typeList = array(
            'string' => 'String',
            'text' => 'Text',
            'number' => 'Number',
            'datetime' => 'DateTime',
            'image' => 'Image'
        );
        return $typeList;
    }

    public function showActiveFieldByDataType($dataType = 'string', $modelData = array()) {

        if ($dataType == NULL) {
            $dataType = 'string';
        }

        $model = NULL;
        $form = NULL;
        $field = NULL;
        $data = NULL;
        $htmlOptions = array();

        if (isset($modelData['model']))
            $model = $modelData['model'];

        if (isset($modelData['field']))
            $field = $modelData['field'];

        if (isset($modelData['data']))
            $data = $modelData['data'];

        if (isset($modelData['htmlOptions']))
            $htmlOptions = $modelData['htmlOptions'];

        $dataType = strtolower($dataType);

        if (strtolower($dataType) == 'string' || strtolower($dataType) == 'number') {
            if ($form != NULL) {
                return $form->activeTextField($model, $field, $htmlOptions);
            } else {
                return CHtml::activeTextField($model, $field, $htmlOptions);
            }
        }

        if ($dataType == 'text') {
            if ($form != NULL) {
                return $form->activeTextArea($model, $field, $htmlOptions);
            } else {
                return CHtml::activeTextArea($model, $field, $htmlOptions);
            }
        }

        if ($dataType == 'array') {
            if ($data == NULL)
                $data = array();
            if ($form != NULL) {
                return $form->activeTextField($model, $field, $htmlOptions);
            } else {
                return CHtml::activeDropDownList($model, $field, $data, $htmlOptions);
            }
        }

        if ($dataType == 'datetime') {
            $oName = explode("_", $field);
            $datetimepicker = $oName[1];
            $htmlOptions = array('data-format' => "yyyy-MM-dd hh:mm:ss", 'type' => "text", 'placeholder' => '时间...');
            $str = '<script  type="text/javascript"> $(function() { $(\'#'.$datetimepicker.'\').datetimepicker({language: \'pt-BR\'});});</script>';
            $str .='<link rel="stylesheet" type="text/css" href="'.Yii::app()->request->baseUrl.'/css/bootstrap-datetimepicker.min.css" /><script  type="text/javascript" src="'.Yii::app()->request->baseUrl.'/js/bootstrap-datetimepicker.min.js"/>';
            $str .='<div class="input-append" id="'.$datetimepicker.'">';
            if ($data == NULL)
                $data = array();
            if ($form != NULL) {
                $str .=$form->activeTextField($model, $field, $htmlOptions);
                $str .='<span class="add-on">
                            <i data-date-icon="icon-calendar" data-time-icon="icon-time" class="icon-calendar">
                            </i>
                        </span>
                    </div> ';
                return $str;
            } else {
                $str .=CHtml::activeTextField($model, $field, $htmlOptions);
                $str .='<span class="add-on">
                            <i data-date-icon="icon-calendar" data-time-icon="icon-time" class="icon-calendar">
                            </i>
                        </span>
                    </div> ';
                return $str;
            }
        }

        if ($dataType == 'image') {
//            $oName = explode("_", $field);
//            $field = 'media_image_' . $oName[2] . '_' . $oName[3];
//            $field = 'image_media_image_attribute';
            $str = '';
            //$str = '<div class="row-fluid"><div class="span6"><nobr style="color: red;font-size:20px">*</nobr>' . 'image' . '</div>';
//            $str .= '<div class="span6">' . CHtml::activeFileField($model, $field);
            $str .= '<div>' . CHtml::activeFileField($model, $field);
            if ($model->$field != NULL) {
                $imageUrl = Yii::app()->request->baseUrl . $model->$field;
                $str.= "<img src=" . $imageUrl . " width=50 height=50 />";
            }

            //$str .= '</div></div>';
            $str .='</div>';

            return $str;
        }
    }

    public function getModelDataByDataType($dataTypeItem) {

        if ($dataTypeItem instanceof BTreeItem) {
            $type = $dataTypeItem->getValue();
            $dataTypeTable = new BASheet('dataTypeData');

            if ($type == 'array') {
                $list = array();
                $dataTypeView = $dataTypeTable->getViewByOwner($dataTypeItem);
                foreach ($dataTypeView as $list) {
                    $keyItem = $list->getItem('key');
                    if ($keyItem instanceof BTreeItem)
                        $key = $keyItem->getValue();

                    $valueItem = $list->getItem('value');
                    if ($valueItem instanceof BTreeItem)
                        $value = $valueItem->getValue();

                    $list[$key] = $value;
                    return $list;
                }
            }
        }
    }

}
